package com.solocredit.finance.ui.steps.impl

import android.content.Context
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.http.ApiService
import com.solocredit.finance.http.ApiService.addCommonParams
import com.solocredit.finance.http.ApiService.addRandomParams
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.http.IHttpCallback
import com.solocredit.finance.mvp.presenter.MvpPresenter
import com.solocredit.finance.ui.steps.view.IMullaStepAccountView
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.MullaUserPointsHelper
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/31 15:46
 * @Annotation：认证流程 法语地区绑卡 Presenter 实现
 */
class MullaStepAccountPresenterImpl(context: Context?) : MvpPresenter<IMullaStepAccountView>(context) {

    /**
     * 获取已绑定的账户列表
     */
    fun loadMullaAccountListAction() {
        mvpView?.showMullaLoading()
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.MULLA_API_ACCOUNT_LIST_FRENCH_PATH)
        val params = JSONObject().addCommonParams().addRandomParams().apply {
//            put("path", ApiService.API_PATH.MULLA_API_ACCOUNT_LIST_FRENCH_PATH)
        }
        HttpHelper.postMullaAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val array = data.optJSONArray("obj")
                        val accountList = arrayListOf<JSONObject>()

                        if (array != null && array.length() > 0) {
                            for (i in 0..<array.length()) {
                                val item = array.optJSONObject(i)
                                item.put("isEdit", false)
                                accountList.add(item)
                            }
                        }

                        if (accountList.size < 2) {
                            for (i in 0..<2 - accountList.size) {
                                val item = JSONObject()
                                item.put("isEdit", true)
                                accountList.add(item)
                            }
                        }
                        mvpView?.showMullaAccountList(accountList)
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showMullaToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }

    /**
     * 添加绑卡
     */
    fun submitMullaBindAccountAction(mobile: String, walletChannel: String, bindFlag:String = "NO"){
        mvpView?.showMullaLoading()
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.MULLA_API_ACCOUNT_ADD_PATH)
        val params = JSONObject().addCommonParams().addRandomParams().apply {
//            put("path", ApiService.API_PATH.MULLA_API_ACCOUNT_ADD_PATH)
            put("walletMobile", mobile)
            put("walletMobileConfirm", mobile)
            put("walletChannel", walletChannel)
            put("addBindFlag", bindFlag)
        }
        HttpHelper.postMullaAction(httpUrl, params, object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                //刷新列表
                loadMullaAccountListAction()
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj") ?: JSONObject()
                        //新增账户成功，需要增加积分
                        MullaUserPointsHelper.saveMullsUserPointsAction("addAccount", MyApp.app.getString(R.string.points_use_info_add_account), MullaCustomConfigsHelper.getMullaAddAccountPoints())

                        // "YES/NO 是否需要提示用户这个号码可以绑另一个渠道的钱包"
                        val addBindFlag = obj.optString("addBindFlag")
                        if (addBindFlag == "YES") {
                            //需要提示绑定另一个渠道账户
                            var otherAccountInfo: JSONObject? = null

                            //用于从APP配置中获取（walletChannels）对应的信息
                            val channel = obj.optString("channel")
                            if (channel.isNotBlank()) {
                                val customize = MullaCustomConfigsHelper.getMullaConfigData()
                                if (customize != null) {
                                    val walletChannels = customize.optJSONArray("walletChannels")
                                    if (walletChannels != null && walletChannels.length() > 0) {
                                        for (i in 0..<walletChannels.length()) {
                                            val item = walletChannels.optJSONObject(i)
                                            if (channel == item.optString("value")) {
                                                otherAccountInfo = item
                                                break
                                            }
                                        }
                                    }

                                    // 只有非空的情况下才处理
                                    if (otherAccountInfo != null) {
                                        otherAccountInfo.put("walletMobile", mobile)
                                        //提示绑定另一个渠道账户
                                        mvpView?.showMullaBingAccountOtherDialog(otherAccountInfo)
                                        return
                                    }
                                }
                            }
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showMullaToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }

    /**
     * 删除账户
     */
    fun deleteMullaAccountAction(ids: String) {
        mvpView?.showMullaLoading()
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.MULLA_API_ACCOUNT_DELETE_PATH)
        val params = JSONObject().addCommonParams().apply {
//            put("path", ApiService.API_PATH.MULLA_API_ACCOUNT_DELETE_PATH)
            put("ids", ids)
        }
        HttpHelper.postMullaAction(httpUrl, params, object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                mvpView?.showMullaToast(data.optString("msg"))
                when(data.optInt("code")) {
                    0 -> {//成功
                        //删除账户成功，需要减少积分
                        MullaUserPointsHelper.saveMullsUserPointsAction("removeAccount", MyApp.app.getString(R.string.points_use_info_remove_account), "-${MullaCustomConfigsHelper.getMullaAddAccountPoints()}")
                        //刷新列表
                        loadMullaAccountListAction()
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showMullaToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }
}